﻿using Hr.IDAL;
using Hr.Model;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Hr.DAL
{
    public class AttendanceDAL
    {
        #region 考勤管理
        // 创建EF对象
        private DbContext db = DbContextFactory.Create();
        //核心dal层代码

        #region 获取所有的考勤信息
        /// <summary>
        /// 获取所有的考勤信息
        /// </summary>
        /// <returns></returns>
        public IEnumerable<object> GetAttendanceList()
        {
            return db.Set<Attendance_List>().OrderByDescending(n => n.pk_Attendance).Select(s => new
            {
                s.pk_Attendance,
                s.TypeID,
                s.CreateDate,
                s.IPAddress,
                s.Description,
                s.StatusID,
                db.Set<Sys_TypeID>().Where(w => w.TableName.Equals("Attendance_List") & w.ID == s.TypeID).FirstOrDefault().TypeName_CHS,
                db.Set<Sys_StatusID>().Where(w => w.TableName.Equals("Attendance_List") & w.ID == s.StatusID).FirstOrDefault().StatusName_CHS,
                db.Set<Sys_StatusID>().Where(w => w.TableName.Equals("Attendance_List") & w.ID == s.StatusID).FirstOrDefault().Visual
            }).ToList();
        }
        #endregion
        #region 新增考勤管理
        /// <summary>
        /// 新增考勤管理
        /// </summary>
        /// <returns></returns>
        public void UpdateAttendance(Attendance_List r, string type,int pk_User)
        {
            if (type.Equals("Add"))
            {
                //添加
                //设置默认属性
                r.CreateDate = DateTime.Now;//当前时间设置为打卡时间 
                r.CreateUser = pk_User;
                r.fk_User = pk_User;
                r.fk_Department = db.Set<User_List>().SingleOrDefault(n => n.pk_User == pk_User).fk_Department;
                //通过userid获取部门信息的上下班时间，进行判断是否在上班之前打卡，否则迟到
                if (int.Parse(DateTime.Now.Hour.ToString()) > 8)
                {
                    r.StatusID = 0;
                }
                else
                {
                    r.StatusID = 1;
                }
                db.Set<Attendance_List>().Add(r);
            }
            else if (type.Equals("Edit"))
            {
                //修改也要修改IP,修改时间
                r.ModifyUser = pk_User;
                r.ModifyDate = DateTime.Now;
                db.Set<Attendance_List>().AddOrUpdate(r);
            }
        }
        #endregion
        #region 根据ID查询考勤信息
        /// <summary>
        /// 根据ID查询考勤信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Attendance_List GetAttendance(int id)
        {
            return db.Set<Attendance_List>().SingleOrDefault(n => n.pk_Attendance == id);
        }
        #endregion
        #region 根据FullName查询Attendance_List表数据
        /// <summary>
        /// 根据FullName查询Attendance_List表数据
        /// </summary>
        /// <returns></returns>
        public IEnumerable<object> FNameSelectAttendanceList(string Description)
        {
            //return db.Set<Attendance_List>().Where(n => n.Description.Contains(Description)).ToList();
            return db.Set<Attendance_List>().OrderByDescending(n => n.pk_Attendance).Where(n=>n.Description.Contains(Description)).Select(s => new
            {
                s.pk_Attendance,
                s.TypeID,
                s.CreateDate,
                s.IPAddress,
                s.Description,
                s.StatusID,
                db.Set<Sys_TypeID>().Where(w => w.TableName.Equals("Attendance_List") & w.ID == s.TypeID).FirstOrDefault().TypeName_CHS,
                db.Set<Sys_StatusID>().Where(w => w.TableName.Equals("Attendance_List") & w.ID == s.StatusID).FirstOrDefault().StatusName_CHS,
                db.Set<Sys_StatusID>().Where(w => w.TableName.Equals("Attendance_List") & w.ID == s.StatusID).FirstOrDefault().Visual
            }).ToList();
        }
        #endregion
        #region 通过表名获取类型
        /// <summary>
        ///通过表名获取类型
        /// </summary>
        /// <returns></returns>
        public List<Sys_TypeID> GetTypeList(string TableName)
        {
            return db.Set<Sys_TypeID>().Where(n => n.TableName.Equals(TableName)).ToList();
        }
        public List<Sys_StatusID> GetStatusList(string TableName)
        {
            return db.Set<Sys_StatusID>().Where(n => n.TableName.Equals(TableName)).ToList();
        }
        #endregion
        #region 编辑、查询考勤信息，包括用户昵称
        /// <summary>
        /// 编辑、查询考勤信息，包括用户昵称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Dictionary<string,object> GetAttendanceFullName(int id)
        {
            Attendance_List AT = db.Set<Attendance_List>().SingleOrDefault(n => n.pk_Attendance == id);
            Dictionary<string, object> dt = new Dictionary<string, object>()
            {
                {"AttendanceInfo",AT },
                {"FullName",db.Set<User_List>().SingleOrDefault(n=>n.pk_User==AT.fk_User).FullName }
            };
            return dt;
        }
        #endregion
        #region 删除考勤信息
        /// <summary>
        /// 删除考勤信息
        /// </summary>
        /// <param name="r"></param>
        public void DelAttendancedata(Attendance_List r)
        {
            db.Set<Attendance_List>().Remove(r);
        }
        #endregion

        #endregion

        #region 考勤周报表
        public List<object> GetWeeklyList(DateTime StartTime, DateTime EndTime, string Term)
        {
            if (Term == null)
            {
                Term = "";
            }

            //获取本周
            DateTime now = DateTime.Now;
            int Y = StartTime.Year;//固定年
            int M = now.Month;
            int D = StartTime.Day;
            List<int> MM = new List<int>();
            for (int i = 0; i < 7; i++)
            {
                MM.Add(StartTime.AddDays(i).Month);
            }
            #region 测试
            //星期一为第一天  
            int weeknow = Convert.ToInt32(now.DayOfWeek);
            //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。  
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;
            //本周第一天  
            DateTime FirstDay = now.AddDays(daydiff);

            //星期天为最后一天  
            int lastWeekDay = Convert.ToInt32(now.DayOfWeek);
            lastWeekDay = lastWeekDay == 0 ? (7 - lastWeekDay) : lastWeekDay;
            int lastWeekDiff = (7 - lastWeekDay);

            //本周最后一天  
            DateTime LastDay = now.AddDays(lastWeekDiff);
            #endregion

            //定义时间转换
            List<object> AttList = new List<object>();
            #region test
            //for (int i = 0; i < 7; i++)
            //{
            //foreach (Attendance_List item in db.Set<Attendance_List>())
            //{
            //    if (GetTime(item.CreateDate.ToString()) >= FirstDay && GetTime(item.CreateDate.ToString()) <= LastDay)
            //    {
            //        //在本周,则添加到本周集合中
            //        NowDayAttList.Add(item);
            //    }
            //}


            //for (int i = 0; i < 7; i++)
            //{
            //    DateTime Now2 = now.AddDays(i);
            //    List<object> Al = new List<object>();
            //    foreach (User_List u in db.Set<User_List>())
            //    {
            //        //循环本周的集合
            //        foreach (Attendance_List item in db.Set<Attendance_List>().Where(n => n.fk_User == u.pk_User))
            //        {
            //            if (DateTime.Parse(item.CreateDate.ToString()).ToLongDateString().Equals(Now2.ToLongDateString()))
            //            {
            //                object o = (from AL in db.Set<Attendance_List>()
            //                            join UL in db.Set<User_List>()
            //                            on AL.fk_User equals UL.pk_User
            //                            join UD in db.Set<User_Department>()
            //                            on AL.fk_Department equals UD.pk_Department
            //                            where UD.DepartmentName.Contains(Term) || UL.FullName.Contains(Term)
            //                            && UL.pk_User==item.fk_User
            //                            && UL.CreateDate==item.CreateDate
            //                            select new
            //                            {
            //                                AL.pk_Attendance,
            //                                UL.FullName,
            //                                UD.DepartmentName,
            //                                AL.CreateDate
            //                                //类型
            //                                //状态
            //                            }).FirstOrDefault();
            //                Al.Add(o);
            //            }
            //        }
            //    }
            //    Dictionary<string, object> dt = new Dictionary<string, object>()
            //        {
            //            {"星期",i },
            //            {"content",Al }
            //        };
            //    AttList.Add(dt);

            //}
            #endregion
            //根据用户进行循环
            foreach (User_List UL in db.Set<User_List>().Where(n => n.FullName.Contains(Term)))
            {

                Dictionary<string, object> dt = new Dictionary<string, object>()
                {
                    {"部门",db.Set<User_Department>().SingleOrDefault(n=>n.pk_Department==UL.fk_Department).DepartmentName },
                    {"人员",UL.FullName },
                    {"周一",GetAttendanceDay(UL.pk_User,Y,MM[0],D)},
                    {"周二",GetAttendanceDay(UL.pk_User,Y,MM[1],D+1) },
                    {"周三",GetAttendanceDay(UL.pk_User,Y,MM[2],D+2) },
                    {"周四",GetAttendanceDay(UL.pk_User,Y,MM[3],D+3) },
                    {"周五",GetAttendanceDay(UL.pk_User,Y,MM[4],D+4) },
                    {"周六",GetAttendanceDay(UL.pk_User,Y,MM[5],D+5) },
                    {"周日",GetAttendanceDay(UL.pk_User,Y,MM[6],D+6) }
                };
                AttList.Add(dt);
            }
            return AttList;
        }

        /// <summary>
        /// 查询每年每月
        /// </summary>
        /// <param name="pk_User"></param>
        /// <param name="Y"></param>
        /// <param name="M"></param>
        /// <param name="D"></param>
        /// <returns></returns>
        private List<object> GetAttendanceDay(int pk_User, int Y, int M, int D)
        {
            List<object> AL = new List<object>();
            //根据ID查询出所有的考勤记录
            foreach (Attendance_List item in db.Set<Attendance_List>().Where(n => n.fk_User == pk_User))
            {
                int MY = Convert.ToDateTime(item.CreateDate.ToString().Split(' ')[0]).Year;
                int MM = Convert.ToDateTime(item.CreateDate.ToString().Split(' ')[0]).Month;
                int MD = Convert.ToDateTime(item.CreateDate.ToString().Split(' ')[0]).Day;
                if (MY == Y & MM == M & MD == D)
                {
                    Dictionary<string, object> it = new Dictionary<string, object>()
                    {
                        {"pk_Attendance",item.pk_Attendance  },
                        {"Type",db.Set<Sys_TypeID>().SingleOrDefault(n=>n.TableName.Equals("Attendance_List")&n.ID==item.TypeID).TypeName_CHS },
                        {"Time",item.CreateDate }
                    };
                    AL.Add(it);
                }
            }

            return AL;
        }
        #endregion

        #region 考勤月报表
        public List<object> GetmonthlyList(DateTime StartTime, string Term)
        {
            if (Term == null)
            {
                Term = "";
            }

                //获取本周
                DateTime now = DateTime.Now;
                int Y = StartTime.Year;//固定年
                int M = StartTime.Month;
                List<int> MM = new List<int>();

                //定义时间转换
                List<object> AttList = new List<object>();

                //根据用户进行循环
                foreach (User_List UL in db.Set<User_List>().Where(n => n.FullName.Contains(Term)))
                {

                    Dictionary<string, object> dt = new Dictionary<string, object>()
                {
                    {"部门",db.Set<User_Department>().SingleOrDefault(n=>n.pk_Department==UL.fk_Department).DepartmentName },
                    {"人员",UL.FullName },
                    {"上班",AttendanceMonth(UL.pk_User, 0,Y,M,0) },
                    {"下班",AttendanceMonth(UL.pk_User, 1,Y,M,0) },
                    {"外出",AttendanceMonth(UL.pk_User, 2,Y,M,0) },
                    {"请假",AttendanceMonth(UL.pk_User, 3,Y,M,0) },
                    {"加班",AttendanceMonth(UL.pk_User, 4,Y,M,0) },
                    {"正常",AttendanceMonth(UL.pk_User, 0,Y,M,1) },
                    {"迟到",AttendanceMonth(UL.pk_User, 1,Y,M,1) },
                    {"早退",AttendanceMonth(UL.pk_User, 2,Y,M,1) },
                    {"旷工",AttendanceMonth(UL.pk_User, 3,Y,M,1) }
                };
                    AttList.Add(dt);
                }
            return AttList;
        }
        public string AttendanceMonth(int pk_User,int TypeID,int Y,int M,int Type)
        {
            int Count = 0;
            if (Type == 0)
            {
                foreach (Attendance_List item in db.Set<Attendance_List>().Where(n => n.TypeID == TypeID&n.fk_User==pk_User))
                {
                    int YY = DateTime.Parse(item.CreateDate.ToString()).Year;
                    int MM = DateTime.Parse(item.CreateDate.ToString()).Month;
                    if (M == MM & Y == YY)
                    {
                        Count++;
                    }
                }
            }
            else
            {
                foreach (Attendance_List item in db.Set<Attendance_List>().Where(n => n.StatusID == TypeID & n.fk_User == pk_User))
                {
                    int YY = DateTime.Parse(item.CreateDate.ToString()).Year;
                    int MM = DateTime.Parse(item.CreateDate.ToString()).Month;
                    if (M == MM & Y == YY)
                    {
                        Count++;
                    }
                }
            }
            
            if (Count == 0)
            {
                return "";
            }
            return Count.ToString();
        }
        #endregion
        //提交
        public bool SaveChanges()
        {
            return db.SaveChanges() > 0;
        }
    }
}
